package com.adopapa.wechatapi.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.apache.log4j.Logger;

public class HttpXUtil {

	protected static Logger logger = Logger.getLogger(HttpXUtil.class);

	public final static String APPLICATION_JSON = "application/json; charset=UTF-8";
	public final static String APPLICATION_FORM_URLENCODED = "application/x-www-form-urlencoded; charset=UTF-8";

	/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl    请求地址
	 * @param requestMethod 请求方式（GET、POST）
	 * @param outputStr     提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */

	public static String httpsRequest(String requestUrl, String requestMethod, //
			String outputStr, Proxy proxy) {
		return httpsRequest(requestUrl, requestMethod, outputStr, APPLICATION_JSON, proxy);
	}

	public static String httpsRequest(String requestUrl, String requestMethod, //
			String outputStr, String contentType, Proxy proxy) {
		String result = null;
		StringBuffer buffer = new StringBuffer();
		try {

//			System.setProperty("https.proxyHost","localhost");
//			System.setProperty("https.proxyPort","9999");

			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(requestUrl);
			HttpsURLConnection httpsUrlConn = null;
			if (proxy != null) {
				httpsUrlConn = (HttpsURLConnection) url.openConnection(proxy);
			} else {
				httpsUrlConn = (HttpsURLConnection) url.openConnection();
			}
			httpsUrlConn.setSSLSocketFactory(ssf);

			httpsUrlConn.setUseCaches(false);
			httpsUrlConn.setConnectTimeout(15000);
			httpsUrlConn.setReadTimeout(300000);
			// 设置请求方式（GET/POST）
			httpsUrlConn.setRequestMethod(requestMethod);
			// httpUrlConn.setRequestProperty("Content-Type", "application/json;
			// charset=UTF-8");
			httpsUrlConn.setRequestProperty("Accept", "application/json");

			if ("GET".equalsIgnoreCase(requestMethod) //
					|| "DELETE".equalsIgnoreCase(requestMethod)) {
				httpsUrlConn.connect();
			}

			// 当有数据需要提交时
			if (null != outputStr) {
				httpsUrlConn.setDoOutput(true);
				httpsUrlConn.setDoInput(true);
				httpsUrlConn.setRequestProperty("content-type", contentType);
				OutputStream outputStream = httpsUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			System.getProperties().put("jdk.http.auth.tunneling.disabledSchemes", "");
			System.getProperties().put("jdk.http.auth.proxying.disabledSchemes", "");

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpsUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpsUrlConn.disconnect();
			result = buffer.toString();
		} catch (ConnectException ce) {
			logger.error("Server connection timed out.");
			ce.printStackTrace();
		} catch (Exception e) {
			logger.error("https request error:{}", e);
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl    请求地址
	 * @param requestMethod 请求方式（GET、POST）
	 * @param outputStr     提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static String httpRequest(String requestUrl, String requestMethod, //
			String outputStr, Proxy proxy) {
		return httpRequest(requestUrl, requestMethod, outputStr, APPLICATION_JSON, proxy);
	}

	public static String httpRequest(String requestUrl, String requestMethod, //
			String outputStr, String contentType, Proxy proxy) {
		String result = null;
		StringBuffer buffer = new StringBuffer();
		try {
			URL url = new URL(requestUrl);
//			Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 9999));
			HttpURLConnection httpUrlConn = null;
			if (proxy != null) {
				httpUrlConn = (HttpURLConnection) url.openConnection(proxy);
			} else {
				httpUrlConn = (HttpURLConnection) url.openConnection();
			}

			httpUrlConn.setUseCaches(false);
			httpUrlConn.setConnectTimeout(5000); // 毫秒
			httpUrlConn.setReadTimeout(3000); // 毫秒

//			System.getProperties().put("proxySet","true");
//			System.getProperties().put("proxyHost","localhost");
//			System.getProperties().put("proxyPort","9999");

			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod) //
					|| "DELETE".equalsIgnoreCase(requestMethod)) {
				httpUrlConn.connect();
			} else {
//				httpUrlConn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
//				httpUrlConn.setRequestProperty("Accept", "application/json");
			}

			// 当有数据需要提交时
			if (null != outputStr) {
				logger.info(outputStr);
				httpUrlConn.setDoOutput(true);
				httpUrlConn.setDoInput(true);
				httpUrlConn.setRequestProperty("content-type", contentType);
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.flush();
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			result = buffer.toString();
		} catch (ConnectException ce) {
			logger.error("Server connection timed out.");
		} catch (Exception e) {
			logger.error("https request error:{}", e);
		}
		return result;
	}

	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("content-type", "text/html");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	// public static void main(String[] args) {
	// Float f = new Float("2.50f");
	// System.out.println(f.intBitsToFloat(0x3EA00E20));
	//
	// byte[] bytes= new byte [] {0x20,0x0E,0xA1,0x3E};
	// }
	//
	// public static int getInt(byte[] bytes) {
	// int result = 0;
	// for (int ii = 0; ii < bytes.length; ii++) {
	// result = result | (0xff & bytes[ii]) << (8 * ii);
	// }
	// return result;
	// }

	public static void main(String[] args) {
		String host = "localhost";
		int port = 9999;
		Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
		String result = httpRequest("http://www.vgomc.com", "GET", null, proxy);
		System.out.println(result);
		result = httpsRequest("https://www.baidu.com", "GET", null, proxy);
		System.out.println(result);
	}
}